//
//  ZHCorrectDrawView.m
//  test02
//
//  Created by lzh on 2020/10/16.
//  Copyright © 2020 NO. All rights reserved.
//

#import "ZHCorrectDrawView.h"

/**

  矫正绘图开始的view

*/

#define UIColorFromRGBA(rgbValue, alphaValue) \
[UIColor \
  colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
         green:((float)((rgbValue & 0x00FF00) >> 8))/255.0 \
          blue:((float)(rgbValue & 0x0000FF))/255.0 \
         alpha:alphaValue]


#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
 blue:((float)(rgbValue & 0xFF))/255.0 \
alpha:1.0]
#import "CircleView.h"
@interface ZHCorrectDrawView()

@property (nonatomic,assign)CGFloat  cornerCircleRedis;
@property (nonatomic,assign)CGFloat  panWidth;
@property (nonatomic,strong)UIColor *panStrokColor;
@property (nonatomic,strong)UIColor *lineStrokColor;


//四个角上的 四个小圆
@property (nonatomic,strong)CircleView *topLeftPoint;
@property (nonatomic,strong)CircleView *topRightPoint;
@property (nonatomic,strong)CircleView *bottomLeftPoint;
@property (nonatomic,strong)CircleView *bottomRightPoint;

@property (nonatomic,assign)CGPoint topLeft;
@property (nonatomic,assign)CGPoint topRight;
@property (nonatomic,assign)CGPoint bottomLeft;
@property (nonatomic,assign)CGPoint bottomRight;

@property (nonatomic,assign)ZHCorrectPointType zh_pointType;

@property (nonatomic,strong)NSArray *pointViews;

@property (nonatomic,strong)NSArray *originPoints;



@property (nonatomic,assign)CGVector transformVector;


@end
@implementation ZHCorrectDrawView

-(instancetype)initWithFrame:(CGRect)frame{
    
    if (self = [super initWithFrame:frame]) {
        
        [self initProperties];
        [self initView];
    }
    
    return self;
}

- (void)initProperties{

    self.originPoints = [NSArray array];

    self.cornerCircleRedis = 7.0;
    self.panWidth = 2.0;
    self.panStrokColor = [UIColor whiteColor];
    self.transformVector = CGVectorMake(0, 0);
    self.lineStrokColor = UIColorFromRGB(0xFF5722);

     self.topLeftPoint = [self createPoint];
     self.topRightPoint = [self createPoint];
     self.bottomLeftPoint = [self createPoint];
     self.bottomRightPoint = [self createPoint];
    
     self.pointViews = @[self.topLeftPoint,self.topRightPoint,self.bottomLeftPoint,self.bottomRightPoint];
}


-(void)initView{
    
    self.backgroundColor = [UIColor clearColor];
    
//    CAShapeLayer * maskLayer  = (CAShapeLayer *)self.layer;
//    maskLayer.fillColor = UIColorFromRGBA(0xD8D8D8, 0.5).CGColor;

    [self addSubview:self.topLeftPoint];
    [self addSubview:self.topRightPoint];
    [self addSubview:self.bottomLeftPoint];
    [self addSubview:self.bottomRightPoint];
}

#pragma mark 创建圆点
- (CircleView *)createPoint{
    CircleView *point = [[CircleView alloc] init];
    point.userInteractionEnabled = NO;
    point.frame = CGRectMake(0, 0, self.cornerCircleRedis * 2, self.cornerCircleRedis * 2);
    point.backgroundColor = [UIColor whiteColor];
    point.layer.cornerRadius = self.cornerCircleRedis;
    point.layer.masksToBounds = YES;
    point.layer.borderWidth = self.panWidth / 2;
    point.layer.borderColor = self.panStrokColor.CGColor;
    
    return point;
}
#pragma mark 更新圆点位置
-(void)updataPoints:(NSArray *)points{
    
    self.originPoints = points;

    self.topLeft = [points[0] CGPointValue];
    self.topRight = [points[1] CGPointValue];
    self.bottomLeft = [points[3] CGPointValue];
    self.bottomRight = [points[2] CGPointValue];
    
    [self setNeedsDisplay];
    
}
#pragma mark 绘画
-(void)drawRect:(CGRect)rect{
    
    [super drawRect:rect];
   

    CAShapeLayer *maskLayer = (CAShapeLayer *)self.layer;

    UIBezierPath  * rectPath = [UIBezierPath bezierPathWithRect:rect];
    UIBezierPath * iregularPath = [UIBezierPath bezierPath];

    [iregularPath moveToPoint:self.topLeft];
    [iregularPath addLineToPoint:self.topRight];
    [iregularPath addLineToPoint:self.bottomRight];
    [iregularPath addLineToPoint:self.bottomLeft];
    [iregularPath closePath];
    [rectPath appendPath:iregularPath];
//
    maskLayer.fillColor = UIColorFromRGBA(0xD8D8D8, 0.5).CGColor;
    maskLayer.fillRule = kCAFillRuleEvenOdd;
    maskLayer.path = rectPath.CGPath;
    
    // 这是纯粹是为了搭配 放大镜而写的
     CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetLineWidth(context, self.panWidth);
//        此处获取颜色要注意不然无法正常显示
        CGColorRef cgColor = self.lineStrokColor.CGColor;
        CGContextSetStrokeColor(context, CGColorGetComponents(cgColor));
        CGContextSetLineCap(context, kCGLineCapRound);
        CGContextSetLineJoin(context, kCGLineJoinRound);

        CGContextMoveToPoint(context, self.topLeft.x, self.topLeft.y);
        CGContextAddLineToPoint(context, self.topRight.x, self.topRight.y);
        CGContextAddLineToPoint(context, self.bottomRight.x, self.bottomRight.y);
        CGContextAddLineToPoint(context, self.bottomLeft.x, self.bottomLeft.y);
        CGContextAddLineToPoint(context, self.topLeft.x, self.topLeft.y);
        CGContextStrokePath(context);
    
       self.topLeftPoint.center = self.topLeft;
       self.topRightPoint.center = self.topRight;
       self.bottomLeftPoint.center = self.bottomLeft;
       self.bottomRightPoint.center = self.bottomRight;
    

}

+ (Class)layerClass{
    return CAShapeLayer.class;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    UITouch * touch = [[touches allObjects]firstObject];
    
    if (!touch) {return;}
    
    [self beginShowBorderColor];
    
    CGPoint point = [touch locationInView:self];
    
    CGFloat len = 1000;
    NSArray *points = @[@(self.topLeft),@(self.topRight),@(self.bottomLeft),@(self.bottomRight)];
    
    for (int i=0; i<points.count; i++) {
        
        CGPoint tempPoint = [points[i] CGPointValue];
        
       CGFloat dis = [self distanceBetweenPointsFirst:point second:tempPoint];
        
        if (dis < len) {//查找离点击的点 最近的 是哪个角 就拖动那个圆点
            
            len = dis;
            
            self.zh_pointType = i;
            
            //防止点击 小圆图 到 点击位置
             self.transformVector = CGVectorMake(point.x - tempPoint.x, point.y - tempPoint.y);
            
        }
        
    }
    
    
}
-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    UITouch * touch = [[touches allObjects]firstObject];
    
    if (!touch) {return;}
    
    CGPoint t_point = [touch locationInView:self];
           
    CGPoint point = CGPointMake(t_point.x - self.transformVector.dx, t_point.y - self.transformVector.dy);
    
    //防止跑出图片范围
    if (point.x < 0) {
        point.x = 0;
    }
    if (point.y < 0) {
        point.y = 0;
    }
    if (point.x > self.bounds.size.width) {
        point.x = self.bounds.size.width;
    }
    if (point.y > self.bounds.size.height) {
        point.y = self.bounds.size.height;
    }
    
    //放大镜回调 tips 此处toView 会出现无法正常显示放大镜的问题 所以相对位置是整个屏幕self.superview!.superview 如果是个self.view 就是整个屏幕的高度，如果次此视图的superview不是的整个屏幕的高度就会显示不正确
    CGPoint centerPoint ;
    
//    if (@available(iOS 13.0,*)) {
//        
//        centerPoint = [self convertPoint:point toView:[[[UIApplication sharedApplication] windows] firstObject]];
//    }else{
//        
//         centerPoint =  [self convertPoint:point toView:[UIApplication sharedApplication].keyWindow];
//    }
    
    centerPoint =  [self convertPoint:point toView:[UIApplication sharedApplication].keyWindow];
  
    
       

    switch (self.zh_pointType) {
        case ZHCorrectPointTopLeft:
            if ([self pointIntTiangleDirection:0 point:point triangle:@[@(self.topRight),@(self.bottomLeft),@(self.bottomRight)]]){
                
                 self.topLeft = point;
            }
           
            break;
            case ZHCorrectPointTopRight:
            
             if ([self pointIntTiangleDirection:1 point:point triangle:@[@(self.topLeft),@(self.bottomLeft),@(self.bottomRight)]]){
                 
                  self.topRight = point;
             }
           
            break;
            case ZHCorrectPointBottomLeft:
             if ([self pointIntTiangleDirection:2 point:point triangle:@[@(self.topLeft),@(self.topRight),@(self.bottomRight)]]){
                 
                  self.bottomLeft = point;
             }
           
            break;
            case ZHCorrectPointBottomRight:
            
            if ([self pointIntTiangleDirection:3 point:point triangle:@[@(self.topLeft),@(self.bottomLeft),@(self.topRight)]]){
                
                 self.bottomRight = point;
            }
           
            break;
        default:
             centerPoint = CGPointMake(-1,-1);
            break;
    }
    
    self.updatePoints(@[@(self.topLeft),
                           @(self.topRight),
                           @(self.bottomRight),
                           @(self.bottomLeft)]);
    
    
    [self setNeedsDisplay];
    
    if (self.updateMagnifierPoint) {
           self.updateMagnifierPoint(centerPoint);
       }
    
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //    判断4个角点是不是，原始的状态
    [self recordIsOrinalState];
    
    [self endShowWihteColor];
    
    [self setNeedsDisplay];
    self.updateMagnifierPoint(CGPointMake(-1,-1));
}

- (void)recordIsOrinalState{
    
    UIView *cuttentTopLeft = self.pointViews[0];
    UIView *cuttentTopRight = self.pointViews[1];
    UIView *cuttentBottomLeft = self.pointViews[2];
    UIView *cuttentBottomRight = self.pointViews[3];
    
    CGPoint originTopLeft = [self.originPoints[0] CGPointValue];
    CGPoint originTopRight = [self.originPoints[1] CGPointValue];
    CGPoint originBottomLeft = [self.originPoints[3] CGPointValue];
    CGPoint originBottomRight = [self.originPoints[2] CGPointValue];
    
    if ((originTopLeft.x == cuttentTopLeft.center.x && originTopLeft.y == cuttentTopLeft.center.y) &&
        (originTopRight.x == cuttentTopRight.center.x && originTopRight.y == cuttentTopRight.center.y) &&
        (originBottomLeft.x == cuttentBottomLeft.center.x && originBottomLeft.y == cuttentBottomLeft.center.y) &&
        (originBottomRight.x == cuttentBottomRight.center.x && originBottomRight.y == cuttentBottomRight.center.y)) {
        NSLog(@"是原点");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kCanRestCorrectRotation" object:@{@"type" : @(2), @"can" : @(NO)}];
    }else{
        NSLog(@"不是原点");
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kCanRestCorrectRotation" object:@{@"type" : @(2), @"can" : @(YES)}];
    }
}

#pragma mark 四角颜色
- (void)beginShowBorderColor{
    self.topLeftPoint.backgroundColor = [UIColor clearColor];
    self.topRightPoint.backgroundColor = [UIColor clearColor];
    self.bottomLeftPoint.backgroundColor = [UIColor clearColor];
    self.bottomRightPoint.backgroundColor = [UIColor clearColor];
}

- (void)endShowWihteColor{
    self.topLeftPoint.backgroundColor = [UIColor whiteColor];
    self.topRightPoint.backgroundColor = [UIColor whiteColor];
    self.bottomLeftPoint.backgroundColor = [UIColor whiteColor];
    self.bottomRightPoint.backgroundColor = [UIColor whiteColor];
}
#pragma mark 两点间距离
- (CGFloat)distanceBetweenPointsFirst:(CGPoint)first second:(CGPoint)second{
    
    CGFloat deltaX = second.x - first.x;
    CGFloat deltaY = second.y - first.y;
    
    return sqrt(deltaX*deltaX + deltaY*deltaY);
}
#pragma mark 滑动范围
- (BOOL)pointIntTiangleDirection:(int)direction point:(CGPoint)point triangle:(NSArray *)triangle{
    
    if (triangle.count == 3) {
        BOOL b0 = [self signPoint0:point point1:[triangle[0] CGPointValue] point2:[triangle[1] CGPointValue]] < 0;
        BOOL b1 = [self signPoint0:point point1:[triangle[0] CGPointValue] point2:[triangle[2] CGPointValue]] < 0;
        BOOL b2 = [self signPoint0:point point1:[triangle[2] CGPointValue] point2:[triangle[1] CGPointValue]]  < 0;
        
        switch (direction) {
            case 0:
                return !b0 && !b1 && !b2;
                break;
            case 1:
                return b0 && b1 && !b2;
                break;
            case 2:
                return !b0 && !b1 && b2;
                break;
            case 3:
                return b0 && b2 && !b1;
                break;
    
            default:
                return NO;
                break;
        }
        
    }
    
    return NO;
}

- (CGFloat)signPoint0:(CGPoint)point0 point1:(CGPoint)point1 point2:(CGPoint)point2{
    return (point0.x - point2.x) * (point1.y - point2.y) - (point1.x - point2.x) * (point0.y - point2.y);
}

#pragma mark 四个圆 超出父试图 可点击
-(BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{

    if (CGRectContainsPoint(self.topLeftPoint.frame, point)||CGRectContainsPoint(self.topRightPoint.frame, point)||CGRectContainsPoint(self.bottomLeftPoint.frame, point)||CGRectContainsPoint(self.bottomRightPoint.frame, point)) {
        
        return YES;
    }
    
    return [super pointInside:point withEvent:event];
}



@end
